package post

import (
	"time"
	"chaoyer/ghost_assist/dao/visitordao"
	"strings"
	"chaoyer/ghost_assist/base/code"
	"chaoyer/ghost_assist/Nets"
	"chaoyer/ghost_assist/utils"
	"github.com/gin-gonic/gin"
	"chaoyer/ghost_assist/entity"
	"io/ioutil"
	"github.com/sirupsen/logrus"
	"net/http"
	"github.com/json-iterator/go"
)

const URL = "https://www.chaoyer.com/ghost/api/v0.1/posts?limit=all"
const URL1 = "https://www.chaoyer.com/ghost/api/v0.1/tags?limit=all"
const clientId = "ghost-frontend"
const clientSecret = "9ef9f3d4aa00"

var PostCache map[string]entity.Post    // 所有文章
var BlogConfig map[string]interface{}   // 网站的数据缓存

func init(){
	loadPost()
	startTimer()
}

// 重新载入文章
func RefreshPost(c *gin.Context){
	loadPost()
	Nets.SendSucess(c)
}

func loadPost(){
	// 所有文章
	PostCache = make(map[string]entity.Post)
	BlogConfig = make(map[string]interface{})
	resp,err:=http.Get(URL+"&client_id="+clientId+"&client_secret="+clientSecret)
	
	if err!=nil{
		logrus.Error(err)
		return
	}
	defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
		// handle error
		logrus.Error(err)
		return
	}


	resp1,err:=http.Get(URL1+"&client_id="+clientId+"&client_secret="+clientSecret)
	if err!=nil{
		logrus.Error(err)
		return
	}
	defer resp.Body.Close()
    body1, err := ioutil.ReadAll(resp1.Body)
    if err != nil {
		// handle error
		logrus.Error(err)
		return
	}

	posts:=jsoniter.Get(body,"posts").GetInterface().([]interface{})
	tags:=jsoniter.Get(body1,"tags").GetInterface().([]interface{})

	BlogConfig["post_total"] = len(posts)    // 文章的总数
	BlogConfig["tag_total"] = len(tags)    // 标签的总数

	for _,v :=range posts{
		var m = v.(map[string]interface{})
		post:=new(entity.Post)
		post.ID = m["id"].(string)
		post.Title = m["title"].(string)
		post.Url = m["url"].(string)
		PostCache[post.ID] = *post
	}
	p,_:=jsoniter.Marshal(PostCache)
	logrus.Infof("加载文章数据---%v",string(p))
}

// 根据名称查询
func Search(c *gin.Context){
	
	search:=c.Query("search")
	if utils.IsBlank(search){
		Nets.SendError(c,code.ARGS_NOT_ENOUGH)
		return
	}
	data :=make([]entity.Post,0)
	for _,v:=range PostCache{
		if strings.Contains(strings.ToLower(v.Title),strings.ToLower(search)){
			pv,_ := visitordao.FindByPostId(v.ID)
			v.Pv = pv.Pv
			data = append(data,v)
		}
	}
	Nets.SendData(c,data)
}

func GetBlogConfig(c *gin.Context){
	Nets.SendData(c,BlogConfig)
}

func startTimer() {
	ticker := time.NewTicker(time.Hour * 1)
    go func() {
        for range ticker.C {
            if time.Now().Format("15") == "00" {
				loadPost()
            }
        }
    }()
}